import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../core/elegance_theme.dart';
import '../../core/elegance_base.dart';

/// 时间选择器组件
/// 参照Element UI的TimePicker控件实现

/// 时间选择器类型枚举
enum ETimePickerType {
  /// 时间选择器
  timePicker,
  
  /// 时间选择（固定时间点）
  timeSelect,
}

/// 时间选择器尺寸枚举
enum ETimePickerSize {
  /// 小型尺寸
  small,
  
  /// 普通尺寸
  normal,
  
  /// 大型尺寸
  large,
}

/// 时间选择器选项类
class ETimePickerOptions {
  /// 创建时间选择器选项
  ETimePickerOptions({
    this.selectableRange,
    this.start = '09:00',
    this.end = '18:00',
    this.step = '00:30',
    this.minTime,
    this.maxTime,
  });
  
  /// 可选时间段，例如'18:30:00 - 20:30:00'或者传入数组['09:30:00 - 12:00:00', '14:30:00 - 18:30:00']
  final dynamic selectableRange; // String or List<String>
  
  /// 开始时间（仅TimeSelect有效）
  final String start;
  
  /// 结束时间（仅TimeSelect有效）
  final String end;
  
  /// 间隔时间（仅TimeSelect有效）
  final String step;
  
  /// 最小时间，小于该时间的时间段将被禁用（仅TimeSelect有效）
  final String? minTime;
  
  /// 最大时间，大于该时间的时间段将被禁用（仅TimeSelect有效）
  final String? maxTime;
}

/// ETimePicker组件
class ETimePicker extends EleganceStatefulWidget {
  /// 创建ETimePicker组件
  const ETimePicker({
    super.key,
    required this.type,
    this.value,
    this.onChanged,
    this.readonly = false,
    this.disabled = false,
    this.editable = true,
    this.clearable = true,
    this.size = ETimePickerSize.normal,
    this.placeholder,
    this.startPlaceholder,
    this.endPlaceholder,
    this.isRange = false,
    this.arrowControl = false,
    this.align = Alignment.centerLeft,
    this.popperClass,
    this.pickerOptions,
    this.rangeSeparator = '-',
    this.valueFormat,
    this.defaultValue,
    this.name,
    this.prefixIcon,
    this.clearIcon,
    this.onBlur,
    this.onFocus,
  });

  /// 时间选择器类型
  final ETimePickerType type;
  
  /// 绑定值（TimePicker为DateTime，TimeSelect为String）
  final dynamic value;
  
  /// 值变更回调
  final ValueChanged<dynamic>? onChanged;
  
  /// 完全只读
  final bool readonly;
  
  /// 禁用
  final bool disabled;
  
  /// 文本框可输入
  final bool editable;
  
  /// 是否显示清除按钮
  final bool clearable;
  
  /// 输入框尺寸
  final ETimePickerSize size;
  
  /// 非范围选择时的占位内容
  final String? placeholder;
  
  /// 范围选择时开始日期的占位内容
  final String? startPlaceholder;
  
  /// 范围选择时结束日期的占位内容
  final String? endPlaceholder;
  
  /// 是否为时间范围选择，仅对TimePicker有效
  final bool isRange;
  
  /// 是否使用箭头进行时间选择，仅对TimePicker有效
  final bool arrowControl;
  
  /// 对齐方式
  final AlignmentGeometry align;
  
  /// TimePicker下拉框的类名
  final String? popperClass;
  
  /// 当前时间日期选择器特有的选项
  final ETimePickerOptions? pickerOptions;
  
  /// 选择范围时的分隔符
  final String rangeSeparator;
  
  /// 可选，仅TimePicker时可用，绑定值的格式。不指定则绑定值为 Date 对象
  final String? valueFormat;
  
  /// 可选，选择器打开时默认显示的时间
  final dynamic defaultValue;
  
  /// 原生属性
  final String? name;
  
  /// 自定义头部图标的类名
  final IconData? prefixIcon;
  
  /// 自定义清空图标的类名
  final IconData? clearIcon;
  
  /// 当 input 失去焦点时触发
  final VoidCallback? onBlur;
  
  /// 当 input 获得焦点时触发
  final VoidCallback? onFocus;

  @override
  State<ETimePicker> createState() => _ETimePickerState();
}

class _ETimePickerState extends EleganceState<ETimePicker> {
  /// 是否显示弹出层
  bool _showPopper = false;
  
  /// 输入框控制器
  final TextEditingController _controller = TextEditingController();
  
  /// 当前值
  dynamic _currentValue;
  
  /// 焦点节点
  final FocusNode _focusNode = FocusNode();
  
  /// 日期格式化器
  late DateFormat _dateFormat;
  
  /// 时间选项列表（仅TimeSelect有效）
  List<String> _timeOptions = [];

  @override
  void initState() {
    super.initState();
    _currentValue = widget.value;
    _dateFormat = DateFormat(widget.valueFormat ?? 'HH:mm:ss');
    _formatValue();
    
    if (widget.type == ETimePickerType.timeSelect) {
      _generateTimeOptions();
    }
    
    _focusNode.addListener(() {
      if (_focusNode.hasFocus && !widget.disabled && !widget.readonly) {
        _showPopper = true;
        if (widget.onFocus != null) {
          widget.onFocus!();
        }
      } else {
        if (widget.onBlur != null) {
          widget.onBlur!();
        }
      }
      setState(() {});
    });
  }

  @override
  void didUpdateWidget(covariant ETimePicker oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.value != widget.value) {
      _currentValue = widget.value;
      _formatValue();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  /// 格式化当前值并设置到输入框
  void _formatValue() {
    if (_currentValue == null) {
      _controller.text = '';
      return;
    }
    
    if (widget.isRange) {
      if (_currentValue is List<DateTime>) {
        List<DateTime> dateList = _currentValue;
        _controller.text = '${_dateFormat.format(dateList[0])} ${widget.rangeSeparator} ${_dateFormat.format(dateList[1])}';
      } else if (_currentValue is List<String>) {
        List<String> stringList = _currentValue;
        _controller.text = '${stringList[0]} ${widget.rangeSeparator} ${stringList[1]}';
      }
    } else {
      if (_currentValue is DateTime) {
        _controller.text = _dateFormat.format(_currentValue);
      } else if (_currentValue is String) {
        _controller.text = _currentValue;
      }
    }
  }

  /// 生成时间选项（仅TimeSelect有效）
  void _generateTimeOptions() {
    if (widget.pickerOptions == null) return;
    
    ETimePickerOptions options = widget.pickerOptions!;
    List<String> optionsList = [];
    
    // 解析开始和结束时间
    List<String> startParts = options.start.split(':');
    List<String> endParts = options.end.split(':');
    List<String> stepParts = options.step.split(':');
    
    int startHour = int.parse(startParts[0]);
    int startMinute = startParts.length > 1 ? int.parse(startParts[1]) : 0;
    int startSecond = startParts.length > 2 ? int.parse(startParts[2]) : 0;
    
    int endHour = int.parse(endParts[0]);
    int endMinute = endParts.length > 1 ? int.parse(endParts[1]) : 0;
    int endSecond = endParts.length > 2 ? int.parse(endParts[2]) : 0;
    
    int stepHour = stepParts.length > 0 ? int.parse(stepParts[0]) : 0;
    int stepMinute = stepParts.length > 1 ? int.parse(stepParts[1]) : 0;
    int stepSecond = stepParts.length > 2 ? int.parse(stepParts[2]) : 0;
    
    // 创建时间对象
    DateTime current = DateTime(2000, 1, 1, startHour, startMinute, startSecond);
    DateTime endTime = DateTime(2000, 1, 1, endHour, endMinute, endSecond);
    
    // 生成时间选项
    while (current.isBefore(endTime) || current.isAtSameMomentAs(endTime)) {
      String formattedTime = _formatTime(current);
      optionsList.add(formattedTime);
      
      // 增加步长
      current = current.add(Duration(
        hours: stepHour,
        minutes: stepMinute,
        seconds: stepSecond,
      ));
    }
    
    _timeOptions = optionsList;
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    if (widget.valueFormat != null) {
      return DateFormat(widget.valueFormat).format(time);
    }
    
    // 根据输入的时间格式判断显示精度
    if (time.second > 0) {
      return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}:${time.second.toString().padLeft(2, '0')}';
    } else {
      return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    }
  }

  /// 处理输入变化
  void _handleInputChange(String value) {
    if (!widget.editable) return;
    
    // 尝试解析输入的时间
    try {
      if (widget.isRange) {
        List<String> parts = value.split(widget.rangeSeparator);
        if (parts.length == 2) {
          String startStr = parts[0].trim();
          String endStr = parts[1].trim();
          
          if (widget.type == ETimePickerType.timePicker) {
            DateTime start = _parseTime(startStr);
            DateTime end = _parseTime(endStr);
            _updateValue([start, end]);
          } else {
            _updateValue([startStr, endStr]);
          }
        }
      } else {
        if (widget.type == ETimePickerType.timePicker) {
          DateTime date = _parseTime(value);
          _updateValue(date);
        } else {
          _updateValue(value);
        }
      }
    } catch (e) {
      // 解析失败，不更新值
    }
  }

  /// 解析时间字符串
  DateTime _parseTime(String timeStr) {
    try {
      return _dateFormat.parse(timeStr);
    } catch (e) {
      // 尝试其他常见格式
      List<String> formats = ['HH:mm', 'HH:mm:ss', 'h:mm a', 'h:mm:ss a'];
      for (String format in formats) {
        try {
          return DateFormat(format).parse(timeStr);
        } catch (e2) {
          continue;
        }
      }
      throw FormatException('Invalid time format');
    }
  }

  /// 更新值
  void _updateValue(dynamic newValue) {
    _currentValue = newValue;
    if (widget.onChanged != null) {
      widget.onChanged!(_currentValue);
    }
    setState(() {});
  }

  /// 处理清除按钮点击
  void _handleClear() {
    if (widget.disabled || widget.readonly || !widget.clearable) return;
    
    _currentValue = null;
    _controller.text = '';
    if (widget.onChanged != null) {
      widget.onChanged!(null);
    }
    setState(() {});
  }

  /// 处理选择时间选项
  void _handleSelectTime(String timeStr) {
    if (widget.type == ETimePickerType.timePicker) {
      DateTime date = _parseTime(timeStr);
      _updateValue(date);
    } else {
      _updateValue(timeStr);
    }
    _controller.text = timeStr;
    _showPopper = false;
  }

  /// 处理选择时间范围
  void _handleSelectRange(String startStr, String endStr) {
    if (widget.type == ETimePickerType.timePicker) {
      DateTime start = _parseTime(startStr);
      DateTime end = _parseTime(endStr);
      _updateValue([start, end]);
    } else {
      _updateValue([startStr, endStr]);
    }
    _controller.text = '$startStr ${widget.rangeSeparator} $endStr';
    _showPopper = false;
  }

  /// 获取输入框样式
  TextStyle _getInputStyle(BuildContext context) {
    EleganceThemeData? theme = EleganceTheme.of(context);
    double fontSize;
    
    switch (widget.size) {
      case ETimePickerSize.small:
        fontSize = 12;
        break;
      case ETimePickerSize.normal:
        fontSize = 14;
        break;
      case ETimePickerSize.large:
        fontSize = 16;
        break;
      default:
        fontSize = 14;
    }
    
    return TextStyle(
      fontSize: fontSize,
      color: widget.disabled ? theme.textPlaceholderColor : theme.textPrimaryColor,
    );
  }

  /// 获取输入框尺寸
  Size _getInputSize() {
    double height;
    
    switch (widget.size) {
      case ETimePickerSize.small:
        height = 28;
        break;
      case ETimePickerSize.normal:
        height = 36;
        break;
      case ETimePickerSize.large:
        height = 44;
        break;
      default:
        height = 36;
    }
    
    return Size.fromHeight(height);
  }

  /// 构建弹出层内容
  Widget _buildPopperContent() {
    if (widget.type == ETimePickerType.timeSelect) {
      return _buildTimeSelectContent();
    } else {
      return _buildTimePickerContent();
    }
  }

  /// 构建TimeSelect内容
  Widget _buildTimeSelectContent() {
    return Container(
      padding: EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 2,
            spreadRadius: 1,
          ),
        ],
      ),
      child: GridView.count(
        crossAxisCount: 4,
        shrinkWrap: true,
        mainAxisSpacing: 8,
        crossAxisSpacing: 8,
        children: _timeOptions.map((time) {
          bool isSelected = false;
          if (widget.isRange) {
            if (_currentValue is List) {
              List valueList = _currentValue;
              isSelected = valueList.contains(time);
            }
          } else {
            isSelected = _currentValue == time;
          }
          
          return InkWell(
            onTap: () => _handleSelectTime(time),
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: isSelected ? Colors.blue : Colors.transparent,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                time,
                style: TextStyle(
                  color: isSelected ? Colors.white : Colors.black87,
                  fontSize: 14,
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建TimePicker内容
  Widget _buildTimePickerContent() {
    // 这里简化实现，实际应该包含时钟表盘或时间输入界面
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 2,
            spreadRadius: 1,
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '时间选择器',
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          // 简化实现，实际应该是时钟表盘或时间输入控件
          ElevatedButton(
            onPressed: () {
              DateTime now = DateTime.now();
              _handleSelectTime(_formatTime(now));
            },
            child: Text('选择当前时间'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    EleganceThemeData? theme = EleganceTheme.of(context);
    Size inputSize = _getInputSize();
    
    return Stack(
      alignment: Alignment.center,
      children: [
        TextField(
          controller: _controller,
          focusNode: _focusNode,
          readOnly: widget.readonly || widget.disabled,
          enabled: !widget.disabled,
          style: _getInputStyle(context),
          decoration: InputDecoration(
            hintText: widget.placeholder,
            hintStyle: TextStyle(color: theme.textPlaceholderColor),
            prefixIcon: widget.prefixIcon != null ? Icon(widget.prefixIcon) : null,
            suffixIcon: widget.clearable && _currentValue != null && !widget.disabled && !widget.readonly
                ? IconButton(
                    icon: Icon(widget.clearIcon ?? Icons.clear),
                    onPressed: _handleClear,
                    splashRadius: 16,
                  )
                : null,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: BorderSide(color: theme.borderColor),
            ),
            contentPadding: EdgeInsets.symmetric(horizontal: 12),
            isDense: true,
          ),
          onChanged: widget.editable ? _handleInputChange : null,
          onTap: () {
            if (!widget.disabled && !widget.readonly) {
              _showPopper = true;
              setState(() {});
            }
          },
        ),
        
        // 弹出层
        if (_showPopper)
          Positioned(
            top: inputSize.height + 8,
            left: 0,
            right: 0,
            child: Container(
              alignment: widget.align,
              child: _buildPopperContent(),
            ),
          ),
        
        // 点击空白处关闭弹出层
        if (_showPopper)
          Positioned.fill(
            child: GestureDetector(
              onTap: () {
                _showPopper = false;
                _focusNode.unfocus();
                setState(() {});
              },
              behavior: HitTestBehavior.translucent,
            ),
          ),
      ],
    );
  }
}